using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using xml_classes;
using QuestPrototype.Screen_Manager;
using QuestPrototype.Screen_Manager.Screens;
using QuestPrototype.Screen_Manager.Screens.Menus;

namespace QuestPrototype
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        const short HEIGHT = 720;
        const short WIDTH = 1280;
        MouseCursor cursor;
        //SpriteBatch spriteBatch;
        Texture2D animation_texture;
        Texture2D background_texture;
        Character girl;
        GameScreen gameScreen;
        //ScreenFromEditor screenFromEditor = new ScreenFromEditor();
        GameMouseState gameMouseState;
        private ScreenManager ScreenManager;

        public Game1()
        {
            Globals.Graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            Window.AllowUserResizing = true;
            this.IsMouseVisible = true;
            Globals.GameSize = new Vector2(WIDTH, HEIGHT);
            Globals.Graphics.PreferredBackBufferWidth = (int)Globals.GameSize.X;
            Globals.Graphics.PreferredBackBufferHeight = (int)Globals.GameSize.Y;
            Globals.Graphics.ApplyChanges();

            Globals.BackBuffer = new RenderTarget2D(Globals.Graphics.GraphicsDevice, (int)Globals.GameSize.X, (int)Globals.GameSize.Y, false, SurfaceFormat.Color, DepthFormat.None, 0, RenderTargetUsage.PreserveContents);

            //screenFromEditor = (ScreenFromEditor)XMLmanager.Deserialize(screenFromEditor.GetType(), @"C:\Users\Karmel\Documents\Visual Studio 2010\Projects\AdventureGame\AdventureGameEditor\bin\Debug\GameScreens\1280x720\1280x720_ScreensProperties.xml");
            //gameScreen.Polygons1 = screenFromEditor._polygons;

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            Globals.SpriteBatch = new SpriteBatch(GraphicsDevice);
            Globals.Content = this.Content;

            // LOAD FONTS, TEXTURES, and SOUNDS
            Fonts.Load();
            Textures.Load();

            // ADD DEFAULT SCREENS
            ScreenManager = new ScreenManager();
            ScreenManager.AddScreen(new TitleScreen());
            ScreenManager.AddScreen(new MainMenu());

            /*
            // TODO: use this.Content to load your game content here
            Dictionary<string, Texture2D> cursors = new Dictionary<string, Texture2D>();
            cursors.Add("normal", Content.Load<Texture2D>(@"normal"));
            cursors.Add("hotspot", Content.Load<Texture2D>(@"hotspot"));
            cursor = new MouseCursor(cursors, Color.White);

            animation_texture = Content.Load<Texture2D>(@"WalkRight");
            Animation WalkRightAnimation = new Animation("WalkRight", animation_texture, 1.0 / 8.0, 220, 389, 8);
            animation_texture = Content.Load<Texture2D>(@"WalkLeft");
            Animation WalkLeftAnimation = new Animation("WalkLeft", animation_texture, 1.0 / 8.0, 220, 389, 8);
            Animation idle_animation = new Animation("Stand", animation_texture, 1.0 / 8.0, 220, 389, 8);

            Dictionary<string, Animation> animations = new Dictionary<string, Animation>();
            animations["WalkRight"] = WalkRightAnimation;
            animations["WalkLeft"] = WalkLeftAnimation;
            animations["idle"] = idle_animation;

            background_texture = Content.Load<Texture2D>(@"1280x720_ScreenBackgroud");
            girl = new Character(new Rectangle(200, 600, 200, 381), animations, "idle", 5);
            gameScreen = new GameScreen(background_texture, @"C:\Users\Karmel\Documents\Visual Studio 2010\Projects\AdventureGame\AdventureGameEditor\bin\Debug\GameScreens\1280x720\1280x720_WalkingMap.Bmp");

            //List<Polygon> poly_list =  xml_parser.getAllPolygons();
            //Console.WriteLine("parsed " + poly_list.Count + " polygons from xml\n");
            */
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {

            /*
            cursor.Update(gameTime);
            readUserInput(gameTime);
            gameMouseState = UserInput.Update(gameScreen);

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            // TODO: Add your update logic here
            girl.Update(gameTime, ((float)girl.GetPosition().Y / (float)HEIGHT));
            */
            base.Update(gameTime);
            Globals.WindowFocused = this.IsActive;
            Globals.GameTime = gameTime;

            //UPDATE OUR SCREENS
            ScreenManager.Update();

            // INPUT UPDATES
            Input.Update();
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            /*GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            Globals.SpriteBatch.Begin();
            //spriteBatch.Draw(animation_texture, new Rectangle(0, 0, 200, 381), new Rectangle(0, 0, 200, 381) ,Color.White);
            gameScreen.Draw(Globals.SpriteBatch);

            girl.Draw(Globals.SpriteBatch, ((float)girl.GetPosition().Y / (float)HEIGHT));
            cursor.Draw(Globals.SpriteBatch);
            Globals.SpriteBatch.End();
             * base.Draw(gameTime);
             */

            Globals.Graphics.GraphicsDevice.SetRenderTarget(Globals.BackBuffer);
            GraphicsDevice.Clear(Color.Black);
            base.Draw(gameTime);

            // DRAW CONTENTS OF OUR SCREEN MANAGER
            ScreenManager.Draw();

            Globals.Graphics.GraphicsDevice.SetRenderTarget(null);

            // DRAW BACKBUFFER TO SCREEN
            Globals.SpriteBatch.Begin();
            Globals.SpriteBatch.Draw(Globals.BackBuffer, new Rectangle(0, 0, Globals.Graphics.GraphicsDevice.Viewport.Width, Globals.Graphics.GraphicsDevice.Viewport.Width), Color.White);

            // TEST SPRITEFONTS
            Globals.SpriteBatch.DrawString(Fonts.Georgia_16, "HELLO WORLD", new Vector2(0, 100), Color.Orange);
            Globals.SpriteBatch.DrawString(Fonts.Arial_8, "HELLO WORLD", new Vector2(0, 130), Color.White);

            // TEST TEXTURES
            Globals.SpriteBatch.Draw(Textures.RadAvatar, new Rectangle(10, 150, 64, 64), new Rectangle(0, 0, 32, 32), Color.Blue);

            Globals.SpriteBatch.End();

        }

        private void readUserInput(GameTime gameTime)
        {
            MouseState mouse_state = Mouse.GetState();

            //mouse left click
            if (mouse_state.LeftButton == ButtonState.Pressed)
            {
                girl.SetPath(null);
                girl.SetPath(GetPath(mouse_state));
                if (girl.PathCount() != -1)
                {
                    girl.Walk();
                }
            }

            Vector2 MousePosition = new Vector2(mouse_state.X, mouse_state.Y);
            bool backToNormal = true;
            foreach (Polygon pol in gameScreen.Polygons1)
            {
                if (pol.contains(MousePosition))
                {
                    cursor.changeCursor("hotspot");
                    backToNormal = false;
                    break;
                }
            }
            if (backToNormal)
            {
                cursor.changeCursor("normal");
            }
            //mouse right click
        }

        private List<Stop> GetPath(MouseState mouse_state)
        {
            List<Stop> PathOfVectors = new List<Stop>();
            if (!(mouse_state.X >= 0 && mouse_state.X <= WIDTH && mouse_state.Y >= 0 && mouse_state.Y <= HEIGHT))
            {
                return PathOfVectors;
            }
            List<Algorithms.PathFinderNode> path = PathFinder.Commands.FindAPath(gameScreen.wallGrid, new System.Drawing.Point(girl.GetPosition().X / 2, girl.GetPosition().Y / 2), new System.Drawing.Point(mouse_state.X / 2, mouse_state.Y / 2));
            if (null == path)
            {
                return null;
            }
            path.Reverse();

            byte LastDierction = 5;
            byte NewDierction = 5;
            Vector2 Tempv2 = new Vector2();
            if (path.Count > 1)
            {
                LastDierction = getDirection(path[0], path[1]);
                for (int i = 2; i < path.Count; i++)
                {
                    NewDierction = getDirection(path[i - 1], path[i]);
                    if (NewDierction != LastDierction)
                    {
                        Tempv2.X = path[i].X;
                        Tempv2.Y = path[i].Y;
                        PathOfVectors.Add(new Stop(Tempv2 * 2, LastDierction));
                        LastDierction = NewDierction;
                    }
                }
            }

            Tempv2.X = path[path.Count - 1].X;
            Tempv2.Y = path[path.Count - 1].Y;
            PathOfVectors.Add(new Stop(Tempv2 * 2, LastDierction));
            return PathOfVectors;
        }
        private byte getDirection(Algorithms.PathFinderNode from, Algorithms.PathFinderNode to)
        {
            if (from.X < to.X && from.Y < to.Y)
            {
                return 3;
            }
            else if (from.X < to.X && from.Y == to.Y)
            {
                return 6;
            }
            else if (from.X < to.X && from.Y > to.Y)
            {
                return 9;
            }
            else if (from.X == to.X && from.Y < to.Y)
            {
                return 2;
            }
            else if (from.X == to.X && from.Y == to.Y)
            {
                return 5;
            }
            else if (from.X == to.X && from.Y > to.Y)
            {
                return 8;
            }
            else if (from.X > to.X && from.Y < to.Y)
            {
                return 1;
            }
            else if (from.X > to.X && from.Y == to.Y)
            {
                return 4;
            }
            else if (from.X > to.X && from.Y > to.Y)
            {
                return 7;
            }
            else
            {
                return 0;
            }

        }
    }
}
